/*
 * Golazo MA4
 * Copyright (C) 2008 Golazo MASHUP AWARD 4th team.
 * http://code.google.com/p/golazo/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * checkNote
 */
function checkNote() {

  var note = $('#form_note');

  var message = $('#form_message')
    .hide();
	
  if (!Golazo.Action.checkNote(note.val())) {
    
	message
	  .text('メモに誤りがあります。メモを確認してください。')
	  .show();
	
	return false;
  }

  return true;
};
checkNote.runat = 'both';

/**
 * serverload
 */
function serverload() {

  // dispatch 
  Golazo.dispatch(function(request, response, session) {

    // 私は誰か
    var me = Golazo.User.find(session.get('me'));
	if (!me)
	  return $('#signin')
	    .layout(/*me*/)
	    .metaRefresh('/signin.html?' + $.param({ url: request.uri }), 3);
	
    // GET
	if (request.method != 'POST') {
      
      var signature = $('#form_signature')
        .val(me.sign());

      var url = request.data.url || ''

      var note = $('#form_note')
        .val(request.data.note || '');

      // メモから位置情報を抽出する
      var kinds = [];
      try {
        kinds = new Golazo.Kinds.get(note.val(), url);
      } catch (e) {
        Jaxer.Log.warn('The remote procedure call failed.', e);
      }

      var where = Golazo.findAll(kinds, function(kind) {
        return kind.latitude && kind.longitude;
      })[0] || Golazo.WHERE_TOKYO;

      var latitude = $('#form_latitude')
        .val(where.latitude);
      
	  var longitude = $('#form_longitude')
        .val(where.longitude);
      
	  var altitude = $('#form_altitude')
        .val(where.altitude);

      // 私を信頼する人を検索する
      var trustedTo = me.findByTrustedTo();

      // 私を信頼する人をリスト表示する
      trustedTo.forEach(function(user) {
		Golazo.User.Subscriber.htmlify(user)
          .appendTo('#subscribers')
          .show();
      });

      return $('#form,#me')
	    .layout(me)
	    .maps();

	// POST
	} else {

	  // 署名は期待どおりか
      var signature = $('#form_signature')
        .val(request.data.signature || '');

	  if (signature.val() !== me.sign())
	    throw new Error('(signature)');

      var note = $('#form_note')
        .val(request.data.note || '');

      var latitude = $('#form_latitude')
        .val(request.data.latitude || '');
      
	  var longitude = $('#form_longitude')
        .val(request.data.longitude || '');
      
	  var altitude = $('#form_altitude')
        .val(request.data.altitude || '');

      // 緯度、経度、高度は期待どおりか
      if (!Golazo.Action.checkLatitude(latitude.val()))
	    throw new Error('(latitude)');

      if (!Golazo.Action.checkLongitude(longitude.val()))
	    throw new Error('(longitude)');

      if (!Golazo.Action.checkAltitude(altitude.val()))
	    throw new Error('(altitude)');

      // メモの購読者 -- Jaxer は同名パラメータに未対応のため
	  var subscribers = [];
	  request.postData.split('&').forEach(function(param) {
	    param = param.split('=');
		if (param[0] == 'subscriber')
		  subscribers.push(decodeURIComponent(param[1] || ''));
	  });

      // 私を信頼する人を検索する
      var trustedTo = me.findByTrustedTo();

      // 私を信頼する人かどうか
	  subscribers = Golazo.findAll(subscribers, function(subscriber) {
        return !!Golazo.find(trustedTo, function() {
          return this.equals(subscriber);
        });
      });

      // 私を信頼する人をリスト表示する
      trustedTo.forEach(function(user) {
        
		if (Golazo.find(subscribers, function() {
          return user.equals(this);
        })) {
          user.subscribed = {};
        }

        Golazo.User.Subscriber.htmlify(user)
          .appendTo('#subscribers')
	      .show();
      });

      // メモは期待どおりか
      if (!checkNote())
        return $('#form,#me')
		  .layout(me)
	      .maps();

      try {
	    
		// メモを保存する
	    action = new Golazo.Action(me);
        action.note = note.val();
        action.latitude = latitude.val();
        action.longitude = longitude.val();
        action.altitude = altitude.val();
        action.save();
	    
        // メモを購読する
		action.subscribe(me);

        // メモを購読する
        subscribers.forEach(function(subscriber) {
          action.subscribe(subscriber);
        });

      } catch (e) {
	    throw new Error(''+e);
	  }
	  
      return $('#succeeded,#me')
	    .layout(me)
        .metaRefresh('/me.html', 3);
	}
  });
};

/**
 * load
 */
function load(layout) {

  $(document.form).submit(function() {
    return checkNote();
  });

  // #form
  if (layout.is('#form')) {
    
	var latitude = $('#form_latitude');
    var longitude = $('#form_longitude');
    var altitude = $('#form_altitude');

    var point = new GLatLng(latitude.val(), longitude.val());
	var zoom = parseInt(altitude.val(), 10);

     // GMap2
   var map = new GMap2(document.getElementById('map'));
    map.addControl(new GSmallMapControl());
    map.setCenter(point, zoom);

    // GMarker
    var icon = new GIcon(G_DEFAULT_ICON);
    icon.image = 'http://maps.google.com/intl/ja_jp/mapfiles/arrow.png';
    icon.shadow = 'http://maps.google.com/intl/ja_jp/mapfiles/arrowshadow.png';
    icon.iconSize = new GSize(39, 34);
    icon.shadowSize = new GSize(39, 34);
    icon.iconAnchor = new GPoint(20, 34);
    icon.dragCrossAnchor = new GPoint(16, 8);

    var marker = new GMarker(point, { icon: icon });
    map.addOverlay(marker);

    // GStreetview
    var pano = new GStreetviewPanorama(document.getElementById('pano'));
	//pano.hide(); //BUG

    // GStreetviewOverlay
    var overlay = new GStreetviewOverlay()
    map.addOverlay(overlay);

    // GStreetviewClient
	var client = new GStreetviewClient();
    client.getNearestPanoramaLatLng(point, function(latlng) {
      if (latlng) {
		$('#pano').show();
		if (pano.isHidden())
		  pano.show();
        pano.setLocationAndPOV(point);
      }
    });

    // GMap2.move
    GEvent.addListener(map, 'move', function() {
      marker.setLatLng(map.getCenter());
    });

	var initialized = 0;

    // GMap2.moveend
    GEvent.addListener(map, 'moveend', function() {
      latitude.val(map.getCenter().lat());
      longitude.val(map.getCenter().lng());

      client.getNearestPanoramaLatLng(map.getCenter(), function(latlng) {
		
		if (latlng) {
		  $('#pano').show();
          if (pano.isHidden())
	        pano.show();
          if (initialized == 0)
	        pano.setLocationAndPOV(map.getCenter());
		
		} else {
		  if (!pano.isHidden())
	        pano.hide();
	      $('#pano').hide();
        }
		
		if (initialized > 0)
	      initialized -= 1;
      });
    });

    // GMap2.zoomend
    GEvent.addListener(map, 'zoomend', function(from, to) {
      altitude.val(to);
    });

    // GStreetview.initialized
	GEvent.addListener(pano, 'initialized', function(location) {
      initialized++;
	  map.setCenter(location.latlng);
    });

    /*
	// GStreetview.error
    GEvent.addListener(pano, 'error', function(reason) {
    });
    */

    var keyword = $('#form_keyword');
    var move = $('#form_move');

    // GClientGeocoder
    var geocoder = new GClientGeocoder();
	
	move.click(function() {
	  if (keyword.val() !== '') {
        geocoder.getLatLng(keyword.val(), function(point) {
	      map.panTo(point);
		});
      }
    });
  }
};
load.runat = 'client';
